<!-- 司机管理 -->
<template>
  <div class="dashboard-container driver customer-list-box">
    <div class="box">
      <el-card class="box-card alert">
        <el-row>
          <el-col :span="8">
            <el-form>
              <el-form-item label="司机账号:">
                <el-input
                  v-model="params.account"
                  style="width:300px"
                  placeholder="请输入司机账号"
                ></el-input>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-form>
              <el-form-item label="司机姓名:">
                <el-input
                  v-model="params.name"
                  style="width:300px"
                  placeholder="请输入司机姓名"
                ></el-input>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-form>
              <el-form-item label="司机手机号:">
                <el-input
                  v-model="params.phone"
                  style="width:300px"
                  placeholder="请输入司机手机号"
                ></el-input>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-row>
          <el-form label-width="73px">
            <el-row type="flex">
              <el-col :span="8">
                <el-form-item label="所属机构:">
                  <Treeselect
                    v-model="params.agentId"
                    :options="treeData"
                    :normalizer="normalizer"
                    :searchable="true"
                    style="width: 88%"
                    placeholder="请选择所属机构"
                    no-options-text="暂无数据"
                    no-results-text="暂无数据"
                    @select="selectAgency"
                  >
                  </Treeselect>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item>
                  <el-button
                    style="width: 80px;"
                    type="primary"
                    @click="searchFn"
                  >搜索</el-button>
                  <el-button @click="resetFn">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-row>
      </el-card>

      <el-card class="box-card alert">
        <el-table :data="driverData">
          <el-table-column
            type="index"
            :index="indexMethod"
            width="100px"
            label="序号"
          >
          </el-table-column>
          <el-table-column
            prop="account"
            label="司机账号"
          > </el-table-column>
          <el-table-column
            prop="name"
            label="司机姓名"
          > </el-table-column>
          <el-table-column
            prop="mobile"
            label="司机电话"
          > </el-table-column>
          <el-table-column
            prop="truck.licensePlate"
            label="关联车辆"
          >

          </el-table-column>
          <el-table-column
            prop="agency"
            label="所属机构"
          >
            <template v-slot="{ row }">
              <div>{{ row.agency.name }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="workStatus"
            label="工作状态"
          >
            <template>
              <div>上班</div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="180px"
            fixed="right"
          >
            <template v-slot="{ row }">
              <el-button
                size="mini"
                type="text"
                @click="checkFn(row)"
              >查看</el-button>
              <span class="zhanggun"></span>
              <el-button
                size="mini"
                type="text"
                @click="OptionsOk(row)"
              >配置车辆</el-button>

            </template>
          </el-table-column>
        </el-table>
        <el-row
          type="flex"
          justify="center"
          style="margin: 30px 0px;"
        >
          <el-col :span="8">
            <el-pagination
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="currentChange"
            >
            </el-pagination>
          </el-col>
        </el-row>
        <!-- 配置车辆弹框 -->
        <el-dialog
          title="提示"
          :visible.sync="dialogVisible"
          width="40%"
        >
          <!-- 司机信息 -->
          <div class="driverMessage">
            <el-row
              type="flex"
              justify="space-between"
              style="padding-left:50px;margin-bottom:20px"
            >
              <el-col :span="12">
                <span>司机编号：{{ driverMessage.userId }}</span>
              </el-col>
              <el-col :span="12">
                <span>司机名称：{{ driverMessage.name }}</span>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              justify="space-between"
              style="padding-left:50px"
            >
              <el-col :span="12">
                <span>司机电话：{{ driverMessage.mobile }}</span>
              </el-col>
              <el-col :span="12">
                <span>所属机构：{{ driverMessage.agency.name }}</span>
              </el-col>
            </el-row>
          </div>
          <!-- 选择框 -->
          <el-row style="margin:30px">
            <span style="font-weight:700;">配置车辆：</span>
            <el-select
              v-model="handleCarInfo.licensePlate"
              style="width:50%"
              @change="changeSelect"
            >
              <el-option
                v-for="item in handleCar"
                :key="item.id"
                :value="item.id"
                :label="item.licensePlate"
              ></el-option>
            </el-select>
          </el-row>
          <!-- 表单 -->
          <el-table
            :data="handleCarTableList"
            border
            style="width: 100%"
          >
            <el-table-column
              fixed
              prop="licensePlate"
              label="车牌号"
            >
            </el-table-column>
            <el-table-column
              fixed
              prop="workStatus"
              label="车辆状态"
              :formatter="transWorkStatus"
            >
              <!-- <template>
                <span>{{ handleCarTableList[0].workStatus===0?'停用':'启用' }}</span>
              </template> -->
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              header-align="center"
            >
              <template #default="{row}">
                <el-button
                  type="text"
                  size="small"
                  @click="aoligeiCheckFn(row)"
                >查看 </el-button>
                <span style="margin:0 5px">|</span>
                <el-button
                  type="text"
                  size="small"
                  style="color:red;"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row
            type="flex"
            justify="center"
            style="margin-top:30px"
          >
            <el-button
              type="danger"
              @click="driverArrangeCar()"
            >确认</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-row>

        </el-dialog>
      </el-card>
    </div>
  </div>
</template>
<script>
import { driverList, truckTypeDetail, getTruckListInDriver, driverArrangeCar } from '@/api/transit'
// 树状机构
import { agencyList } from '@/api/institutions'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'Courses',
  components: { Treeselect },
  data() {
    return {
      // 列表数据
      driverData: [],
      params: {
        page: 1,
        pageSize: 10,
        account: '', // 司机编号 账号
        agentId: null, // 机构id
        name: '', // 司机名称
        phone: ''// 手机号
      },
      total: null,
      // 所属机构数据
      treeData: [],
      // 点击那一行的司机信息
      driverMessage: {
        account: '', // 司机账号
        name: '', // 司机姓名
        mobile: '', // 司机账号
        agency: {
          name: ''
        }
      },
      // 车辆详情
      truckDetail: {},
      // 配置车辆弹框控制变量
      dialogVisible: false,
      // 获取司机配置车辆弹出框中所有已停用车辆下拉的数据（已停用并且绑定司机数少于两个）
      handleCar: [],
      // 配置司机弹框信息
      handleCarInfo: {
        // 司机对应的车牌
        licensePlate: ''
      },
      handleCarTableList: [{
        // 车牌
        licensePlate: '',
        // 工作状态 0：停用 1：启用
        workStatus: null
      }],
      myuseIdFlag: '',
      currentIndex: null,
      mycurrentIndex: null
    }
  },
  created() {
    this.driverList()
    // 树形所属机构
    this.agencyList()
  },
  methods: {
    // 列表
    async driverList() {
      const res = await driverList(this.params)
      console.log('我是列表数据', res)
      console.log('我是总页数', res.data.counts)
      this.total = Number(res.data.counts)
      this.driverData = res.data.items
      // this.params.page = 1
    },
    async agencyList() {
      const res = await agencyList()

      const treeData = JSON.parse(res.data)
      this.treeData = treeData
      // console.log('我是转换后的树形', treeData)
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    selectAgency(val) {
      // console.log('我是选中的值', val)
      this.params.agentId = val.id
    },

    currentChange(val) {
      // console.log(val)
      this.params.page = val
      this.driverList()
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.driverList()
    },
    searchFn() {
      this.driverList()
      this.params.page = 1
    },
    resetFn() {
      this.params = {
        page: 1,
        pageSize: 10,
        account: '', // 司机编号 账号
        agentId: null, // 机构id
        name: '', // 司机名称
        phone: ''// 手机号
      }
      this.driverList()
    },
    checkFn(row) {
      console.log('我是row', row)
      const id = row.userId
      const trueid = row.id
      localStorage.setItem('driverId', id)
      localStorage.setItem('driverTrueId', trueid)
      this.$router.push(`driver-detail?id=${id}&formUrlName=司机管理`)
    },
    // 配置车辆弹框
    async OptionsOk(row) {
      console.log('我是点击配置司机那一行的数据', row)
      this.driverMessage = row
      // 设置车辆id
      const id = this.driverMessage.truck.id
      console.log('车辆id', id)
      this.myuseIdFlag = id
      // 调用车辆详情
      const res = await truckTypeDetail(id)
      this.truckDetail = res.data
      console.log('我是车辆详情', this.truckDetail)
      this.handleCarInfo.licensePlate = this.truckDetail.id
      this.$confirm(`
      <p>配置车辆需满足以下条件：</p>
      <p>1&nbsp;司机信息已完善&nbsp&nbsp&nbsp&nbsp2&nbsp;司机已设置排班</p>
      <p>3&nbsp;司机绑定车辆未在启用状态</p>
      `, '车辆配置', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          // 先调接口再显示弹框
          // 获取司机配置车辆弹出框中所有已停用车辆下拉的数据（已停用并且绑定司机数少于两个）
          const res = await getTruckListInDriver()
          const handleCar = res.data
          // console.log(handleCar)
          this.handleCar = handleCar
          const arr = this.handleCar.map((item, index) => {
            if (item.id === this.myuseIdFlag) {
              this.currentIndex = index
              return { licensePlate: item.licensePlate, workStatus: item.workStatus }
            }
          })
          // console.log('我是过滤后的table数据1', arr[this.currentIndex])
          // this.handleCarTableList[0] = arr[this.mycurrentIndex] 待测
          this.handleCarTableList.splice(0, 1, arr[this.currentIndex])

          this.dialogVisible = true
        } catch (err) {
          console.log(err)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    changeSelect(val) {
      // console.log('我是改变后选择的', val)
      // console.log(this.handleCar)

      const arr = this.handleCar.map((item, index) => {
        if (item.id === val) {
          // 记录下当前索引状态
          // console.log('我是选择的index', index)
          this.currentIndex = index
          return { licensePlate: item.licensePlate, workStatus: item.workStatus }
        }
      })
      console.log('我是过滤后的table数据2', arr[this.currentIndex])
      // this.handleCarTableList[0] = arr[this.currentIndex]
      this.handleCarTableList.splice(0, 1, arr[this.currentIndex])
      // console.log(222, this.handleCarTableList[0])
    },
    transWorkStatus(row) {
      const key = {
        0: '停用',
        1: '启用'
      }
      if (this.handleCarTableList[0] !== undefined) {
        return key[row.workStatus]
      } else {
        return '该车辆不是已停用车辆好宝儿'
      }
    },
    aoligeiCheckFn() {
      console.log(this.handleCarInfo.licensePlate)
      const id = this.handleCarInfo.licensePlate
      // 点击查看跳转到车辆详情
      this.$router.push(`vehicle-detail?id=${id}`)
    },
    async driverArrangeCar() {
      const res = await driverArrangeCar({ driverIds: [this.driverMessage.userId], truckId: this.handleCarInfo.licensePlate })
      if (res.code === 1) {
        this.$message.error(res.msg)
      } else {
        this.$message.success('操作成功')
        this.driverList()
        this.dialogVisible = false
      }
    },
    indexMethod(index) {
      // console.log(index)
      return index + 1 + (this.params.page - 1) * this.params.pageSize
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.box{
  padding: 20px;
}
.alert {
  margin: 10px 0px;
}
.pagination {
  margin-top: 40px;
}
// 下拉框
::v-deep .el-select {
  width: 100%;
}

::v-deep .el-card{
  overflow: initial;
}
</style>

